package com.lwl.leetcode;

/**
 * @author lwl
 * @Description TODO
 * @date 2023/7/25 0:08
 */
public class Code02AddTwoNum {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode root = new ListNode(-1);
        ListNode t = root;
        int carry = 0;
        while (l1 != null && l2 != null) {
            t.next = new ListNode((l1.val + l2.val + carry) % 10);
            carry = (l1.val + l2.val + carry) / 10;
            t = t.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            t.next = new ListNode((l1.val + carry) % 10);
            carry = (l1.val + carry) / 10;
            t = t.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            t.next = new ListNode((l2.val + carry) % 10);
            carry = (l2.val + carry) / 10;
            t = t.next;
            l2 = l2.next;
        }
        if (carry != 0) {
            t.next = new ListNode(carry);
        }
        return root.next;
    }







    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode res = head;
        int carry = 0;
        while (l1 != null && l2 != null) {
            head.next = new ListNode((l1.val + l2.val + carry) % 10);
            carry = (l1.val + l2.val + carry) / 10;
            l1 = l1.next;
            l2 = l2.next;
            head = head.next;
        }
        while (l1 != null) {
            head.next = new ListNode((l1.val + carry) % 10);
            carry = (l1.val + carry) / 10;
            l1 = l1.next;
            head = head.next;
        }
        while (l2 != null) {
            head.next = new ListNode((l2.val + carry) % 10);
            carry = (l2.val + carry) / 10;
            l2 = l2.next;
            head = head.next;
        }
        if (carry != 0) {
            head.next = new ListNode(carry);
        }
        return res.next;
    }

}
